// 任务管理应用

// DOM元素
const taskInput = document.getElementById('task-input');
const addTaskBtn = document.getElementById('add-task');
const taskList = document.getElementById('task-list');
const emptyState = document.getElementById('empty-state');
const taskCount = document.getElementById('task-count');
const clearCompletedBtn = document.getElementById('clear-completed');
const filterBtns = document.querySelectorAll('.filter-btn');
const currentDateElement = document.getElementById('current-date');

// 当前过滤器
let currentFilter = 'all';

// 初始化应用
function initApp() {
    // 显示当前日期
    updateCurrentDate();
    
    // 加载任务
    loadTasks();
    
    // 更新UI
    updateUI();
    
    // 添加事件监听器
    addEventListeners();
}

// 添加事件监听器
function addEventListeners() {
    // 添加任务
    addTaskBtn.addEventListener('click', addTask);
    taskInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addTask();
    });
    
    // 清除已完成任务
    clearCompletedBtn.addEventListener('click', clearCompletedTasks);
    
    // 过滤器按钮
    filterBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            currentFilter = btn.dataset.filter;
            updateFilterButtons();
            renderTasks();
        });
    });
}

// 更新当前日期显示
function updateCurrentDate() {
    const now = new Date();
    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    currentDateElement.textContent = now.toLocaleDateString('zh-CN', options);
}

// 添加任务
function addTask() {
    const taskText = taskInput.value.trim();
    
    if (taskText) {
        const task = {
            id: Date.now(),
            text: taskText,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        // 获取现有任务
        const tasks = getTasks();
        tasks.push(task);
        
        // 保存任务
        saveTasks(tasks);
        
        // 更新UI
        renderTasks();
        updateTaskCount();
        updateEmptyState();
        updateClearButtonState();
        
        // 清空输入框
        taskInput.value = '';
        taskInput.focus();
    }
}

// 获取任务列表
function getTasks() {
    const tasks = localStorage.getItem('tasks');
    return tasks ? JSON.parse(tasks) : [];
}

// 保存任务列表
function saveTasks(tasks) {
    localStorage.setItem('tasks', JSON.stringify(tasks));
}

// 加载任务
function loadTasks() {
    renderTasks();
    updateTaskCount();
    updateEmptyState();
    updateClearButtonState();
}

// 渲染任务列表
function renderTasks() {
    const tasks = getTasks();
    
    // 根据过滤器筛选任务
    const filteredTasks = tasks.filter(task => {
        if (currentFilter === 'active') return !task.completed;
        if (currentFilter === 'completed') return task.completed;
        return true; // 'all' filter
    });
    
    // 清空任务列表
    taskList.innerHTML = '';
    
    // 添加筛选后的任务
    filteredTasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskList.appendChild(taskElement);
    });
}

// 创建单个任务元素
function createTaskElement(task) {
    const li = document.createElement('li');
    li.className = 'task-item';
    li.dataset.id = task.id;
    
    // 常规模式
    li.innerHTML = `
        <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
        <span class="task-text ${task.completed ? 'completed' : ''}">${escapeHtml(task.text)}</span>
        <div class="task-actions">
            <button class="edit-btn" title="编辑">
                <i class="fas fa-edit"></i>
            </button>
            <button class="delete-btn" title="删除">
                <i class="fas fa-trash-alt"></i>
            </button>
        </div>
    `;
    
    // 添加事件监听器
    const checkbox = li.querySelector('.task-checkbox');
    const editBtn = li.querySelector('.edit-btn');
    const deleteBtn = li.querySelector('.delete-btn');
    
    checkbox.addEventListener('change', () => toggleTaskCompletion(task.id));
    editBtn.addEventListener('click', () => enterEditMode(li, task));
    deleteBtn.addEventListener('click', () => deleteTask(task.id));
    
    return li;
}

// 进入编辑模式
function enterEditMode(taskElement, task) {
    const editInput = document.createElement('input');
    editInput.type = 'text';
    editInput.className = 'edit-input';
    editInput.value = task.text;
    
    const saveBtn = document.createElement('button');
    saveBtn.className = 'save-btn';
    saveBtn.textContent = '保存';
    
    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'cancel-btn';
    cancelBtn.textContent = '取消';
    
    const editContainer = document.createElement('div');
    editContainer.className = 'edit-container';
    editContainer.style.display = 'flex';
    editContainer.style.alignItems = 'center';
    editContainer.style.width = '100%';
    
    editContainer.appendChild(editInput);
    editContainer.appendChild(saveBtn);
    editContainer.appendChild(cancelBtn);
    
    // 保存原始内容，以便取消时恢复
    const originalContent = taskElement.innerHTML;
    
    // 替换为编辑模式
    taskElement.innerHTML = '';
    taskElement.appendChild(editContainer);
    
    // 自动聚焦
    editInput.focus();
    
    // 保存按钮事件
    saveBtn.addEventListener('click', () => {
        const newText = editInput.value.trim();
        if (newText) {
            updateTask(task.id, { text: newText });
        }
        renderTasks();
    });
    
    // 取消按钮事件
    cancelBtn.addEventListener('click', () => {
        taskElement.innerHTML = originalContent;
        // 重新绑定事件
        const checkbox = taskElement.querySelector('.task-checkbox');
        const editBtn = taskElement.querySelector('.edit-btn');
        const deleteBtn = taskElement.querySelector('.delete-btn');
        
        checkbox.addEventListener('change', () => toggleTaskCompletion(task.id));
        editBtn.addEventListener('click', () => enterEditMode(taskElement, task));
        deleteBtn.addEventListener('click', () => deleteTask(task.id));
    });
    
    // 按Enter保存，按Escape取消
    editInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            const newText = editInput.value.trim();
            if (newText) {
                updateTask(task.id, { text: newText });
            }
            renderTasks();
        } else if (e.key === 'Escape') {
            taskElement.innerHTML = originalContent;
            // 重新绑定事件
            const checkbox = taskElement.querySelector('.task-checkbox');
            const editBtn = taskElement.querySelector('.edit-btn');
            const deleteBtn = taskElement.querySelector('.delete-btn');
            
            checkbox.addEventListener('change', () => toggleTaskCompletion(task.id));
            editBtn.addEventListener('click', () => enterEditMode(taskElement, task));
            deleteBtn.addEventListener('click', () => deleteTask(task.id));
        }
    });
}

// 切换任务完成状态
function toggleTaskCompletion(taskId) {
    const tasks = getTasks();
    const taskIndex = tasks.findIndex(task => task.id === taskId);
    
    if (taskIndex !== -1) {
        tasks[taskIndex].completed = !tasks[taskIndex].completed;
        saveTasks(tasks);
        
        // 更新UI
        renderTasks();
        updateTaskCount();
        updateClearButtonState();
    }
}

// 更新任务
function updateTask(taskId, updates) {
    const tasks = getTasks();
    const taskIndex = tasks.findIndex(task => task.id === taskId);
    
    if (taskIndex !== -1) {
        tasks[taskIndex] = { ...tasks[taskIndex], ...updates };
        saveTasks(tasks);
        
        // 更新UI
        updateTaskCount();
    }
}

// 删除任务
function deleteTask(taskId) {
    let tasks = getTasks();
    tasks = tasks.filter(task => task.id !== taskId);
    saveTasks(tasks);
    
    // 更新UI
    renderTasks();
    updateTaskCount();
    updateEmptyState();
    updateClearButtonState();
}

// 清除已完成任务
function clearCompletedTasks() {
    let tasks = getTasks();
    tasks = tasks.filter(task => !task.completed);
    saveTasks(tasks);
    
    // 更新UI
    renderTasks();
    updateTaskCount();
    updateEmptyState();
    updateClearButtonState();
}

// 更新过滤器按钮状态
function updateFilterButtons() {
    filterBtns.forEach(btn => {
        if (btn.dataset.filter === currentFilter) {
            btn.classList.add('active');
        } else {
            btn.classList.remove('active');
        }
    });
}

// 更新任务数量显示
function updateTaskCount() {
    const tasks = getTasks();
    const activeTasks = tasks.filter(task => !task.completed).length;
    
    if (activeTasks === 1) {
        taskCount.textContent = '1 个待完成任务';
    } else {
        taskCount.textContent = `${activeTasks} 个待完成任务`;
    }
}

// 更新空状态显示
function updateEmptyState() {
    const tasks = getTasks();
    const hasTasks = tasks.length > 0;
    
    if (hasTasks) {
        emptyState.style.display = 'none';
        taskList.style.display = 'block';
    } else {
        emptyState.style.display = 'block';
        taskList.style.display = 'none';
    }
}

// 更新清除按钮状态
function updateClearButtonState() {
    const tasks = getTasks();
    const hasCompletedTasks = tasks.some(task => task.completed);
    
    clearCompletedBtn.disabled = !hasCompletedTasks;
}

// 更新UI
function updateUI() {
    updateFilterButtons();
    updateTaskCount();
    updateEmptyState();
    updateClearButtonState();
}

// HTML转义函数，防止XSS攻击
function escapeHtml(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// 当页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);